package com.cloud.wms.ui.returned.inventory;

import android.app.DatePickerDialog;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Message;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

import com.cloud.core.config.IntentKey;
import com.cloud.core.eventBus.Event;
import com.cloud.core.eventBus.EventBusUtil;
import com.cloud.core.utils.DateUtil;
import com.cloud.core.utils.NumberUtils;
import com.cloud.wms.R;
import com.cloud.wms.base.BaseBarActivity;
import com.cloud.wms.config.EventConfig;
import com.cloud.wms.tools.DatePickerUtils;
import com.cloud.wms.ui.in.contract.InInventoryContract;
import com.cloud.wms.ui.in.presnter.InInventoryPresenter;
import com.cloud.wms.ui.returned.entity.InventoryInfoEntity;
import com.cloud.wms.widget.dialog.AlertDialogBuilder;

import java.util.Date;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * @Author:Chen
 * @Date: 2021-01-23 10:18
 * @Description:
 */
public class EditBatchActivity extends BaseBarActivity<InInventoryPresenter> implements InInventoryContract.View {
    @BindView(R.id.btn_submit)
    TextView btnSubmit;
    @BindView(R.id.tv_produce_date)
    TextView tvProduceDate;
    @BindView(R.id.tv_deadline_date)
    TextView tvDeadlineDate;
    @BindView(R.id.tv_in_date)
    TextView tvInDate;
    @BindView(R.id.et_shelf_life)
    EditText etShelfLife;
    private DatePickerDialog mDateDialog;
    private InventoryInfoEntity.CommodityListBean.BatchInfoBean batchInfo;

    @Override
    protected String barTitle() {
        return "录入批次";
    }

    @Override
    protected int getResId() {
        return R.layout.activity_returned_inventory_edit_batch;
    }

    @Override
    protected void setupComponent() {
    }

    @Override
    protected void initEvent() {
        batchInfo = getIntent().getParcelableExtra(IntentKey.INFO_KEY);
        if (batchInfo == null) {
            btnSubmit.setEnabled(false);
            tvInDate.requestFocus();
            tvInDate.setText(DateUtil.format_yyyy_MM_dd(System.currentTimeMillis()));
        } else {
            btnSubmit.setEnabled(true);
            tvInDate.requestFocus();
            tvInDate.setText(batchInfo.getInDate());
            tvDeadlineDate.setText(batchInfo.getExpirationDate());
            tvProduceDate.setText(batchInfo.getProductionDate());
        }
    }

    private void verifyRequired() {
        String produceDate = tvProduceDate.getText().toString().trim();
        if (TextUtils.isEmpty(produceDate)) {
            btnSubmit.setEnabled(false);
            return;
        }
        String deadlineDate = tvDeadlineDate.getText().toString().trim();
        if (TextUtils.isEmpty(deadlineDate)) {
            btnSubmit.setEnabled(false);
            return;
        }
        String inDate = tvInDate.getText().toString().trim();
        if (TextUtils.isEmpty(inDate)) {
            btnSubmit.setEnabled(false);
            return;
        }
        btnSubmit.setEnabled(true);
    }

    private void dateSelector(TextView textView, boolean isTodayAfter) {
        mDateDialog = DatePickerUtils.datePicker(this,
                isTodayAfter,
                (view, year, month, dayOfMonth) -> {
                    String date = DateUtil.formatYMD(year, month + 1, dayOfMonth);
                    textView.setText(date);
                    verifyRequired();
                });
        mDateDialog.show();
    }

    private void verifySubmit() {
        String produceDate = tvProduceDate.getText().toString().trim();
        if (TextUtils.isEmpty(produceDate)) {
            info("生产日期为必填项");
            return;
        }
        String deadlineDate = tvDeadlineDate.getText().toString().trim();
        if (TextUtils.isEmpty(deadlineDate)) {
            info("截止日期为必填项");
            return;
        }
        String inDate = tvInDate.getText().toString().trim();
        if (TextUtils.isEmpty(inDate)) {
            info("入库时间为必填项");
            return;
        }
        if (batchInfo == null)
            batchInfo = new InventoryInfoEntity.CommodityListBean.BatchInfoBean();
        batchInfo.setProductionDate(produceDate);
        batchInfo.setExpirationDate(deadlineDate);
        batchInfo.setInDate(inDate);
        EventBusUtil.sendEvent(new Event(EventConfig.SWITCH_BATCH, batchInfo));
        success("批次录入成功！");
        this.finish();
    }

    @Override
    public void onSuccess(Message message) {
    }

    @OnClick({R.id.tv_produce_date, R.id.iv_produce_date, R.id.tv_deadline_date, R.id.iv_deadline_date, R.id.tv_in_date, R.id.iv_in_date, R.id.tv_calculate, R.id.btn_submit})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.tv_produce_date:
            case R.id.iv_produce_date:
                dateSelector(tvProduceDate, false);
                break;
            case R.id.tv_deadline_date:
            case R.id.iv_deadline_date:
                dateSelector(tvDeadlineDate, true);
                break;
            case R.id.tv_in_date:
            case R.id.iv_in_date:
                dateSelector(tvInDate, true);
                break;
            case R.id.tv_calculate:
                calculateDate();
                verifyRequired();
                break;
            case R.id.btn_submit:
                verifySubmit();
                break;
        }
    }

    private void calculateDate() {
        int shelfLife = NumberUtils.getIntegerValue(etShelfLife.getText().toString());
        if (shelfLife <= 0) {
            info("保质期必须大于0");
            return;
        }
        String produceDate = tvProduceDate.getText().toString().trim();
        String deadlineDate = tvDeadlineDate.getText().toString().trim();
        if (TextUtils.isEmpty(produceDate) && TextUtils.isEmpty(deadlineDate)) {
            info("请录入生产日期或截止日期");
            return;
        }
        if (!TextUtils.isEmpty(produceDate) && !TextUtils.isEmpty(deadlineDate)) {
            new AlertDialogBuilder(this)
                    .setTitle("提示")
                    .setMessage("已录入相应日期，是否覆盖其中一个？")
                    .setPositiveButton("生产日期", (dialog, which) -> {
                        Date date = DateUtil.string2Date(deadlineDate, DateUtil.FORMAT_3);
                        String newDate = DateUtil.format_yyyy_MM_dd(DateUtil.addOrSubDay(date, -shelfLife));
                        tvProduceDate.setText(newDate);
                    })
                    .setNegativeButton("到期日期", (dialog, which) -> {
                        Date date = DateUtil.string2Date(produceDate, DateUtil.FORMAT_3);
                        String newDate = DateUtil.format_yyyy_MM_dd(DateUtil.addOrSubDay(date, shelfLife));
                        tvDeadlineDate.setText(newDate);
                    })
                    .show();
            return;
        }
        if (!TextUtils.isEmpty(produceDate)) {
            Date date = DateUtil.string2Date(produceDate, DateUtil.FORMAT_3);
            String newDate = DateUtil.format_yyyy_MM_dd(DateUtil.addOrSubDay(date, shelfLife));
            tvDeadlineDate.setText(newDate);
            return;
        }
        if (!TextUtils.isEmpty(deadlineDate)) {
            Date date = DateUtil.string2Date(deadlineDate, DateUtil.FORMAT_3);
            String newDate = DateUtil.format_yyyy_MM_dd(DateUtil.addOrSubDay(date, -shelfLife));
            tvProduceDate.setText(newDate);
            return;
        }
    }

    public static void start(Context context) {
        Intent intent = new Intent(context, EditBatchActivity.class);
        context.startActivity(intent);
    }

    public static void start(Context context, InventoryInfoEntity.CommodityListBean.BatchInfoBean batchInfo) {
        Intent intent = new Intent(context, EditBatchActivity.class);
        intent.putExtra(IntentKey.INFO_KEY, batchInfo);
        context.startActivity(intent);
    }
}
